package com.farm.iproject.service.impl;

import com.farm.iproject.domain.SearchRecord;
import com.farm.core.time.TimeTool;
import org.apache.log4j.Logger;
import com.farm.iproject.dao.SearchrecordDaoInter;
import com.farm.iproject.service.SearchrecordServiceInter;
import com.farm.parameter.FarmParameterService;
import com.farm.wsch.index.pojo.IndexResult;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：检索记录服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class SearchrecordServiceImpl implements SearchrecordServiceInter {
	@Resource
	private SearchrecordDaoInter searchrecordDaoImpl;

	private static final Logger log = Logger.getLogger(SearchrecordServiceImpl.class);

	@Override
	@Transactional
	public SearchRecord insertSearchrecordEntity(SearchRecord entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		// entity.setCuser(user.getId());
		// entity.setCtime(TimeTool.getTimeDate14());
		// entity.setCusername(user.getName());
		// entity.setEuser(user.getId());
		// entity.setEusername(user.getName());
		// entity.setEtime(TimeTool.getTimeDate14());
		// entity.setPstate("1");
		return searchrecordDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public SearchRecord editSearchrecordEntity(SearchRecord entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		SearchRecord entity2 = searchrecordDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setResultid(entity.getResultid());
		entity2.setSearchtime(entity.getSearchtime());
		entity2.setTimes(entity.getTimes());
		entity2.setRules(entity.getRules());
		entity2.setWord(entity.getWord());
		entity2.setCtime(entity.getCtime());
		entity2.setCuser(entity.getCuser());
		entity2.setSize(entity.getSize());
		entity2.setPstate(entity.getPstate());
		entity2.setId(entity.getId());
		searchrecordDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteSearchrecordEntity(String id, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		searchrecordDaoImpl.deleteEntity(searchrecordDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public SearchRecord getSearchrecordEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return searchrecordDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createSearchrecordSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "WSCH_R_SEARCH A LEFT JOIN ALONE_AUTH_USER B ON A.CUSER=B.ID",
				"A.ID AS ID,A.RESULTID AS RESULTID,A.SEARCHTIME AS SEARCHTIME,A.TIMES AS TIMES,A.RULES AS RULES,A.WORD AS WORD,A.CTIME AS CTIME,A.CUSER AS CUSER,A.SIZE AS SIZE,A.PSTATE AS PSTATE,B.NAME AS USERNAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public void record(String projectid, String word, IndexResult result, LoginUser currentUser) {
		SearchRecord record = new SearchRecord();
		record.setCtime(TimeTool.getTimeDate14());
		record.setCuser(currentUser != null ? currentUser.getId() : null);
		record.setPstate("1");
		record.setResultid(result.getResultId());
		String rulesJson = formatInfoJson(result.getRuleinfos());
		if (rulesJson.length() > 2048) {
			rulesJson = formatInfoJson("rules length " + rulesJson.length() + ",is too long!");
		}
		record.setRules(rulesJson);
		record.setSearchtime(result.getSearchTime());
		record.setSize(result.getTotalSize());
		record.setTimes(formatInfoJson(result.getTimeinfos()));
		record.setProjectid(projectid);
		record.setWord(word);
		searchrecordDaoImpl.insertEntity(record);
	}

	private String formatInfoJson(Object obj) {
		String string = JSON.toJSONString(obj);
		return string;
	}

	@Override
	@Transactional
	public List<String> getHotWord(String projectid, String projectKey, int size) {
		List<Map<String, Object>> hots = searchrecordDaoImpl.getHotWord(projectid);
		Collections.sort(hots, new Comparator<Map<String, Object>>() {
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				return ((BigInteger) o2.get("num")).intValue() - ((BigInteger) o1.get("num")).intValue();
			}
		});
		List<Entry<String, String>> white_list = FarmParameterService.getInstance().getDictionaryList("HOTWORD_WHITE");
		List<Entry<String, String>> black_list = FarmParameterService.getInstance().getDictionaryList("HOTWORD_BLACK");
		Set<String> black_Set = new HashSet<>();
		{// 构造黑名单字典（白名单和黑名单都要加进来，因为白名单会强制添加，所以数据库查出来的数据不要加入白名单中存在的word）
			for (Entry<String, String> node : black_list) {
				if (node.getKey().equals(projectid) || node.getKey().equals(projectKey)
						|| node.getKey().equals("ALL")) {
					black_Set.add(node.getValue().trim());
				}
			}
			for (Entry<String, String> node : white_list) {
				if (node.getKey().equals(projectid) || node.getKey().equals(projectKey)
						|| node.getKey().equals("ALL")) {
					black_Set.add(node.getValue().trim());
				}
			}
		}
		// 添加白名单
		List<Map<String, Object>> overhots = new ArrayList<>();
		for (Entry<String, String> node : white_list) {
			if (node.getKey().equals(projectid) || node.getKey().equals(projectKey) || node.getKey().equals("ALL")) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("word", node.getValue());
				map.put("num", 0);
				overhots.add(map);
			}
		}
		for (Map<String, Object> node : hots) {
			// 剔除黑名单
			if (!black_Set.contains(node.get("word").toString().trim())) {
				// 剔除超长检索词
				if (node.get("word").toString().trim().length() < 64) {
					overhots.add(node);
				}
			}
		}
		List<String> words = new ArrayList<String>();
		for (int n = 0; n < overhots.size() && n < size; n++) {
			words.add((String) overhots.get(n).get("word"));
		}
		return words;
	}
}
